package com.jianggy.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author jianggy
 * @version 1.0
 * @time 2019/11/29 16:00
 * @see
 **/
public class App {
    public static void main(String[] args){
        String url = "jdbc:mysql://localhost:3306/test";
        String driverClass = "com.mysql.jdbc.Driver";
        String username = "root";
        String psw = "1qaz!QAZ";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        try {
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url,username,psw);
            connection.setAutoCommit(false);
            connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            Statement statement = connection.createStatement();
            ResultSet resultSet =  statement.executeQuery("SELECT name,height,version FROM test where id=1 ");
            resultSet.next();
            System.out.println("查询后休眠40s");
            // TimeUnit.SECONDS.sleep(20);
            int height = resultSet.getInt("height");
            long version = resultSet.getLong("version");
            System.out.println("App:"+height);
            String updatesql = "update  test set height='ddddddd', version="+System.currentTimeMillis()+" where  id=1 and version="+version;
            System.out.println(updatesql);
            int res = statement.executeUpdate(updatesql);
            TimeUnit.SECONDS.sleep(40);
            System.out.println("提交事务");
            connection.commit();
            if (res==1){
                System.out.println("App提交成功,修改为"+(height+1));
            }else{
                System.out.println("App修改失败");
            }

        }catch (Exception e){
            System.out.println(format.format(new Date())+"====");
            e.printStackTrace();
        }

    }
}
